package main

import (
	"fmt"
	"time"
)

func msgGen(name string,done chan struct{})chan string{
	c:=make(chan string)
	go func() {
		i:=0
		for{
			select {
			case <-time.After(time.Second*5):
				c<-fmt.Sprintf(name+"message %d",i)
			case <-done:
				fmt.Println("done receive single")
				time.Sleep(time.Second)
				fmt.Println("done finish")
				done<- struct{}{}
				return
			}
			i++
		}
	}()
	return c
}

func fanIn(c1 chan string,c2 chan string)chan string{
	c:=make(chan string)
	go func() {
		for{
			time.Sleep(1*time.Second)
			c<-<-c1
		}
	}()
	go func() {
		for{
			time.Sleep(3*time.Second)
			c<-<-c2
		}
	}()
	return c
}

func fanInBySelect(c1,c2 chan string)chan string{
	c:=make(chan string)
	go func() {
		for{
			select {
			case m:=<-c1:
				c<-m
			case m:=<-c2:
				c<-m
			}
		}
	}()
	return c
}

func getStringNoBlocking(c chan string)(string,bool){
	select {
	case m:=<-c:
		return m,true
	default:
		return "",false
	}
}

func timeOutWait(c chan string,du time.Duration)(string,bool){
	select {
	case m:=<-c:
		return m,true
	case <-time.After(du):
		return "",false
	}
}

func main() {
	//c1:=msgGen("server1")
	done:=make(chan struct{})
	c2:=msgGen("server2",done)
	for i:=0;i<5;i++ {
		//fmt.Println(<-c1)
		if m,ok:=timeOutWait(c2,2*time.Second);ok{
			fmt.Println(m)
		}else{
			fmt.Println("NO message from s2")
		}
	}
	done<- struct{}{}
	//time.Sleep(time.Second)
	<-done
}
